#!/usr/bin/env bash

set -o errexit
set -o xtrace

test_dir=$(realpath $(dirname $0))
. ${test_dir}/functions

MONGO_VERSION=${MONGODB_VERSION:-"3.6"}

desc 'RUN RESTORE ON NEW CLUSTER TEST'

desc 'Start cluster'
start_cluster "$MONGO_VERSION"

desc 'Create test user and role'
mongo_run "db.getSiblingDB(\"admin\").createRole({ \"role\": \"testRole1\",\"privileges\": [{ \"resource\": { \"anyResource\": true },\"actions\": [ \"anyAction\" ]}],\"roles\": []});" "rs1"
mongo_run "db.getSiblingDB(\"admin\").createUser({user: \"testUser1\",pwd: \"test1234\",\"roles\" : [{ \"db\" : \"admin\", \"role\" : \"testRole1\" }]});" "rs1"

desc 'Add test data'
mongo_run "for (var i = 1; i <= 50000; i++) db.getSiblingDB(\"test\").testts.insert( { x : Date.now(), y: i } )" "rs1"

testdb_hash_og=$(mongo_run "db.getSiblingDB(\"test\").runCommand( { dbHash: 1 } ).md5" "rs1" | tail -n 1 | tr -d '\r')
roles_og=$(mongo_run "db.getSiblingDB(\"admin\").system.roles.find({}, {_id: 1}).sort({_id: -1})" rs1 | grep '{ "_id" : "' | awk -F\" '{print$4}')
users_og=$(mongo_run "db.getSiblingDB(\"admin\").system.users.find({}, {_id: 1}).sort({_id: -1})" rs1 | grep '{ "_id" : "' | awk -F\" '{print$4}')

desc 'Configure PBM'
pbm_run config --file=/etc/pbm/aws.yaml
sleep 1
wait_rsync
pbm_run list

desc 'Backup'
pbm_run backup
wait_backup

desc 'Destroy cluster'
docker-compose -f ${test_dir}/docker/docker-compose.yaml rm -fs

desc 'Start a new cluster'
start_cluster "$MONGO_VERSION"

desc 'Create test user and role'
mongo_run "db.getSiblingDB(\"admin\").createRole({ \"role\": \"testRole2\",\"privileges\": [{ \"resource\": { \"anyResource\": true },\"actions\": [ \"anyAction\" ]}],\"roles\": []});" "rs1"
mongo_run "db.getSiblingDB(\"admin\").createUser({user: \"testUser2\",pwd: \"test1234\",\"roles\" : [{ \"db\" : \"admin\", \"role\" : \"testRole2\" }]});" "rs1"

desc 'Configure PBM'
pbm_run config --file=/etc/pbm/aws.yaml
sleep 1
wait_rsync
pbm_run list

desc 'Restore'
pbm_run restore $BCP_NAME
wait_restore

testdb_hash_re=$(mongo_run "db.getSiblingDB(\"test\").runCommand( { dbHash: 1 } ).md5" "rs1" | tail -n 1 | tr -d '\r')
roles_re=$(mongo_run "db.getSiblingDB(\"admin\").system.roles.find({}, {_id: 1}).sort({_id: -1})" rs1 | grep '{ "_id" : "' | awk -F\" '{print$4}')
users_re=$(mongo_run "db.getSiblingDB(\"admin\").system.users.find({}, {_id: 1}).sort({_id: -1})" rs1 | grep '{ "_id" : "' | awk -F\" '{print$4}')

desc 'Check the data'
compare "$testdb_hash_og" "$testdb_hash_re"
compare_arrays "$roles_og" "$roles_re"
compare_arrays "$users_og" "$users_re"

desc 'Destroy cluster'
destroy_cluster
